package com.google.code.netbuilder.dal.providers.jpa;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.google.code.netbuilder.dal.entities.Port;
import com.google.code.netbuilder.dal.providers.IPortProvider;
/**
 * Class is JPA implementation of DAO for Port Entity
 * Uses EntityManager from PersistenceContext
 * @author Sergey Kozlov
 * 
 *
 */
@Stateless
public class PortProviderJPA implements IPortProvider, Serializable{

	private static final long serialVersionUID = -1720001908374790733L;

	@PersistenceContext(unitName = "NetBuilder")
    EntityManager em;
	
	public PortProviderJPA() {
		
	}
	@Override
	public void save(Port entity) throws RuntimeException {
		em.persist(entity);
	}

	@Override
	public void update(Port entity) throws RuntimeException {
		em.merge(entity);
	}
    
	public void refresh() throws RuntimeException {
		em.getEntityManagerFactory().getCache().evictAll();
	}

	@Override
	public void delete(Port entity) throws RuntimeException {
		em.remove(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Port> findAll() throws RuntimeException {
		Query q = em.createQuery("select p from Port p");
		return (List<Port>)q.getResultList();
	}

	@Override
	public Port findByID(Integer id) throws RuntimeException {
		Query q = em.createQuery("select p from Port p where p.id = :id").setParameter("id", id);
		return (Port)q.getSingleResult();
	}

}
